package io.finer.erp.jeecg.bas.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Lists;
import com.google.api.client.util.Maps;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasMaterialTemp;
import io.finer.erp.jeecg.bas.entity.BasMeasureUnit;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrder;
import io.finer.erp.jeecg.bas.mapper.BasMaterialCategoryMapper;
import io.finer.erp.jeecg.bas.mapper.BasMaterialMapper;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasMaterialTempService;
import io.finer.erp.jeecg.bas.service.IBasMeasureUnitService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.stock.entity.StkInventory;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.entity.StkMaterielStorage;
import io.finer.erp.jeecg.stock.mapper.StkIoBillEntryMapper;
import io.finer.erp.jeecg.stock.mapper.StkIoBillMapper;
import io.finer.erp.jeecg.stock.vo.ScanIO;
import io.finer.erp.jeecg.stock.vo.SumQtyVo;
import io.finer.erp.jeecg.stock.vo.SumQtyVo2;

/**
 * @Description: 物料
 * @Author: jeecg-boot
 * @Date:   2020-08-25
 * @Version: V1.0
 */
@Service
public class BasMaterialServiceImpl extends ServiceImpl<BasMaterialMapper, BasMaterial> implements IBasMaterialService {
	@Autowired
	private IBasMaterialCategoryService service;
	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;
	@Autowired
	private BasMaterialMapper basMaterialMapper;
	@Autowired
	private IBasMeasureUnitService unitService;
	@Autowired
	private IBasMaterialTempService tempService;
	@Autowired
	private BasMaterialCategoryMapper basMaterialCategoryMapper;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private ISysBaseAPI baseApi;
	@Autowired
	private StkIoBillMapper stkIoBillMapper;
	@Autowired
	private StkIoBillEntryMapper stkIoBillEntryMapper;
	@Autowired
	private IZrkQzOrderService orderService;
	
	/**
	 * @Description: 添加生成物料编码的方法 并同时生成图片
	 * @param categoryId
	 * @return
	 * Create at: 2020-08-17 15:21:29
	 * @author: duanyong
	 * Revision:
	 *    2020-08-15 15:21:29 - first revision by duanyong
	 *        
	 */
	@Override
	public BasMaterial getMaterialCode(String categoryId) {
		BasMaterialCategory category = service.getById(categoryId);
		String topCode = category.getCode();
		String code = this.getCode(topCode);
		BasMaterial result = null;
		
		if (StringUtils.isNotBlank(code)) {
			result = new BasMaterial().setCode(code);
			
//			String codePath = this.createCodeImg(code);
//			result.setCodeImg(codePath);
		}
		
		return result;
	}

	@Override
	public Result<Object> stopWarning(List<String> idList, Result<Object> result) {
		if (null == idList || 0 == idList.size()) {
			return result.error500("未传入ID");
		}
		
		UpdateWrapper<BasMaterial> wrapper = new UpdateWrapper<>();
		wrapper.in("id", idList);
		BasMaterial material = new BasMaterial();
		material.setIsStop(1);
		
		boolean flag = this.update(material, wrapper);
		if (flag) {
			return result.success("成功停止");
		}
		
		return result.error500("停止失败");
	}

	/**
	 * @Description: 批量生成物料
	 * @param categoryId
	 * @param number
	 * @return
	 * Create at: 2020-08-31 11:45:50
	 * @author: duanyong
	 * Revision:
	 *    2020-08-31 11:45:50 - first revision by duanyong
	 *    2020-10-17 11:42:57 - 修改为物料信息先存入物料临时表中    
	 */
	@Override
	public Result<?> batchAdd(String categoryId, Integer number, String userName) {
		Result<Object> result = new Result<>();
		BasMaterialCategory category = this.service.getById(categoryId);
		if (null == category) {
			return result.error500("查不到该物料分类");
		}
		if (null == number || 0 >= number) {
			return result.error500("请传入一个正整数");
		}
		
		String topCode = category.getCode();
		List<BasMaterialTemp> addList = Lists.newArrayList();
		Date date = DateUtil.date();
		for (int i = 0; i < number; i++) {
			String code = this.getCode(topCode);
//			String codeImg = this.createCodeImg(code);
			BasMaterialTemp material = new BasMaterialTemp();
			material.setCode(code);
			material.setCategoryId(categoryId);
			material.setName(category.getName());
			material.setUnitId(category.getUnitId());
			material.setSupplierId(category.getSupplierId());
			
			//获取物料相关宽度属性
			String categoryName = category.getName();
			String[] strs = categoryName.split("-");
			String lastStr = strs[strs.length-1];
			BigDecimal width = null;
			if(NumberUtil.isInteger(lastStr)) {
				width = NumberUtil.toBigDecimal(lastStr);
			}
			if(null != width) {
				material.setWidth(width);
			}
			
			if(null == userName || userName.length() == 0) {
				LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				if(null != sysUser) {
					material.setCreateBy(sysUser.getUsername());
				}
			} else {
				material.setCreateBy(userName);
			}
			material.setCreateTime(date);
			addList.add(material);
		}
		if (addList.size() != 0) {
			boolean flag = this.tempService.saveBatch(addList);
			if (flag) {
				List<Map<String, String>> resultList = Lists.newArrayList();
				Iterator<BasMaterialTemp> it = addList.iterator();
				String unitName = "";
				BasMeasureUnit unit = this.unitService.getById(category.getUnitId());
				if(null != unit) {
					unitName = unit.getName();
				}
				while(it.hasNext()) {
					BasMaterialTemp material = it.next();
					
					String model = "";
					if(material.getWidth() != null) {
						model = material.getWidth().toString() + "*";
					}
					Map<String, String> map = Maps.newHashMap();
					map.put("code", material.getCode());
					map.put("name", material.getName());
					map.put("model", model);
					map.put("unit", unitName);
					map.put("number", "");
					resultList.add(map);
				}
				result.setResult(resultList);
				return result.success("操作成功");
			}
		}
		
		return result.error500("操作失败");
	}
	
	/**
	 * @Description 创建条码图片
	 * @param code 条码code值
	 * @return
	 * Create at: 2020-08-31 11:58:32
	 * @author: duanyong
	 * Revision:
	 *    2020-08-31 11:58:32 - first revision by duanyong
	 *        
	 */
	public String createCodeImg(String code) {
		if (StringUtils.isNotBlank(code)) {
			
			String ctxPath = uploadpath;
			String fileName = code + ".png";
			String barPath = "bar";
			String imgPath = ctxPath + File.separator + barPath + File.separator;
//			boolean flag = BarCodeUtils.generateLocalBarCode(code, imgPath, fileName);
			fileName = StringUtils.replace(fileName, "/", "");
			File file = QrCodeUtil.generate(code, 300, 300, FileUtil.file(imgPath + fileName));
			if (null == file || !file.exists()) {
				return null;
			}
			barPath = barPath + File.separator + fileName;
			if (barPath.contains("\\")) {
				barPath = barPath.replace("\\", "/");
			}
			return barPath;
		}
		
		return code;
	}
	
	/**
	 * @Description 获取物料编码
	 * @return
	 * Create at: 2020-08-31 14:23:31
	 * @author: duanyong
	 * Revision:
	 *    2020-08-31 14:23:31 - first revision by duanyong
	 *        
	 */
	public String getCode(String categoryCode) {
		String key = "material_no";
		String code = baseApi.getNoByCode(key);
		return new StringBuffer(categoryCode).append(code).toString();
	}

	@Override
	public List<BasMaterial> selectMaterialByCategoryId(String categoryId) {
		return basMaterialMapper.selectMaterialByCategoryId(categoryId);
	}

	@Override
	public BasMaterial getMaterialByCode(String code) {
		LambdaQueryWrapper<BasMaterial> query = new LambdaQueryWrapper<>();
		query.eq(BasMaterial::getCode, code);
		return this.getOne(query);
	}

	@Override
	public List<String> getSuplierMaterialId(String suplierId, String categoryId) {
		return this.baseMapper.getSuplierMaterialId(suplierId, categoryId);
	}

	@Override
	public Result<?> batchAdd(String categoryId, Integer number) {
		return this.batchAdd(categoryId, number, null);
	}

	@Override
	public List<BasMaterial> getByIds(Collection<String> ids) {
		if(null == ids || ids.isEmpty()) {
			return null;
		}
		LambdaQueryWrapper<BasMaterial> query = new LambdaQueryWrapper<>();
		query.in(BasMaterial::getId, ids);
		return list(query);
	}

	@Override
	public List<BasMaterial> getByCodes(List<String> codes) {
		if(codes == null || codes.size() == 0) {
			return Lists.newArrayList();
		}
		LambdaQueryWrapper<BasMaterial> query = new LambdaQueryWrapper<>();
		query.in(BasMaterial::getCode, codes);
		List<BasMaterial> list = this.list(query);
		return list;
	}

	@Override
	public Result<?> batchAddAccessories(String batchCategoryId, Integer batchNum, String userName, String model) {
		Result<Object> result = new Result<>();
		BasMaterialCategory category = this.service.getById(batchCategoryId);
		if (null == category) {
			return result.error500("查不到该物料分类");
		}
		if (null == batchNum || 0 >= batchNum) {
			return result.error500("请传入一个正整数");
		}
		
		String topCode = category.getCode();
		List<BasMaterialTemp> addList = Lists.newArrayList();
		Date date = DateUtil.date();
		for (int i = 0; i < batchNum; i++) {
			String code = this.getCode(topCode);
//			String codeImg = this.createCodeImg(code);
			BasMaterialTemp material = new BasMaterialTemp();
			material.setCode(code);
			material.setCategoryId(batchCategoryId);
			material.setName(category.getName());
			material.setUnitId(category.getUnitId());
			material.setSupplierId(category.getSupplierId());
			material.setModel(model);
			
			//获取物料相关宽度属性
			String categoryName = category.getName();
			String[] strs = categoryName.split("-");
			String lastStr = strs[strs.length-1];
			BigDecimal width = null;
			if(NumberUtil.isInteger(lastStr)) {
				width = NumberUtil.toBigDecimal(lastStr);
			}
			if(null != width) {
				material.setWidth(width);
			}
			
			if(null == userName || userName.length() == 0) {
				LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				if(null != sysUser) {
					material.setCreateBy(sysUser.getUsername());
				}
			} else {
				material.setCreateBy(userName);
			}
			material.setCreateTime(date);
			
			addList.add(material);
		}
		if (addList.size() != 0) {
			boolean flag = this.tempService.saveBatch(addList);
			if (flag) {
				List<Map<String, String>> resultList = Lists.newArrayList();
				Iterator<BasMaterialTemp> it = addList.iterator();
				String unitName = "";
				BasMeasureUnit unit = this.unitService.getById(category.getUnitId());
				if(null != unit) {
					unitName = unit.getName();
				}
				while(it.hasNext()) {
					BasMaterialTemp material = it.next();
					String returnModel = material.getModel();
					Map<String, String> map = Maps.newHashMap();
					map.put("code", material.getCode());
					map.put("name", material.getName());
					map.put("model", returnModel);
					map.put("unit", unitName);
					map.put("number", "");
					resultList.add(map);
				}
				result.setResult(resultList);
				return result.success("操作成功");
			}
		}
		
		return result.error500("操作失败");
	}

	@Override
	public BasMaterial getOneMaterialByCategory(String bcpID) {
		LambdaQueryWrapper<BasMaterial> query = new LambdaQueryWrapper<>();
		query.eq(BasMaterial::getCategoryId, bcpID);
		Page<BasMaterial> page = new Page<BasMaterial>(1, 1);
		IPage<BasMaterial> pageList = page(page, query);
		if(null != pageList.getRecords() && 0 < pageList.getRecords().size()) {
			return pageList.getRecords().get(0);
		}
		return null;
	}
	
	public BasMaterial createMaterialByCategory(String categoryId) {
		BasMaterial material = new BasMaterial();
		material.setCategoryId(categoryId);
		material.setCreateBy("admin");
		material.setCreateTime(DateUtils.getDate());
		BasMaterialCategory category = this.categoryService.getById(categoryId);
		String cateCode = category.getCode();
		material.setCode(this.getCode(cateCode));
		material.setName(category.getName());
		material.setUnitId(category.getUnitId());
		material.setSupplier(category.getSupplierId());
		material.setVersion(1);
		
		this.save(material);
		return material;
	}

	@Override
	public List<String> getInventoryMaterialIdsByCategory(String categoryId) {
		// TODO Auto-generated method stub
		return this.basMaterialMapper.getInventoryMaterialIdsByCategory(categoryId);
	}

	@Override
	public List<BasMaterial> selectDistinctMaterialByCategoryId(String categoryId) {
		// TODO Auto-generated method stub
		return this.basMaterialMapper.selectDistinctMaterialByCategoryId(categoryId);
	}

	@Override
	public void changeMaterialCPCategory(StkIoBill stkIoBill, List<StkIoBillEntry> stkIoBillEntryList) {
		// TODO Auto-generated method stub
		String ioType = stkIoBill.getStockIoType();
		String first = ioType.substring(0, 1);
		boolean inFlag = false;
		boolean transFlag = false;
		if("1".equals(first)) {
			inFlag = true;
		} else if ("3".equals(first)) {
			transFlag = true;
		}
		Iterator<StkIoBillEntry> iterator = stkIoBillEntryList.iterator();
		while(iterator.hasNext()) {
			StkIoBillEntry entry = iterator.next();
			String warehouseId = null;
			if(inFlag) {
				warehouseId = entry.getWarehouseId();
			}
			if(transFlag) {
				warehouseId = entry.getInWarehouseId();
			}
			if(CommonConstant.CP_CATEGORY_ID.equals(warehouseId)) {
				String materialId = entry.getMaterialId();
				BasMaterial material = getById(materialId);
				String categoryId = material.getCategoryId();
//				BasMaterialCategory cpCategory = this.categoryService.getCPCategory(categoryId);
				material.setCategoryId(categoryId);
				updateById(material);
			}
		}
	}

	@Override
	public Result<?> batchAdd(ScanIO scanIo) {
		// TODO Auto-generated method stub
		Integer batchNum = scanIo.getBatchNum();
		if(null == batchNum || 0 == batchNum.intValue()) {
			return Result.error("请传入打印数量。");
		}
		BigDecimal length = scanIo.getLength();
		BigDecimal width = scanIo.getWidth();
		String unitId = scanIo.getUnit();
		String number = scanIo.getNumber();
		if(StringUtils.isBlank(number)) {
			return Result.error("请填写数量。");
		}
		if(StringUtils.isBlank(unitId)) {
			return Result.error("请填写单位。");
		}
		String categoryId = scanIo.getCategoryId();
		if(StringUtils.isBlank(categoryId)) {
			return Result.error("请选择分类。");
		}
		BasMeasureUnit unit = this.unitService.getById(unitId);
		if(null == unit) {
			return Result.error("请选择单位。");
		}
		//如果输入的是张，则转换为平方
		BigDecimal numberDecimal = new BigDecimal(number);
		BigDecimal pageNum = null;
		if(unit.getName().equals("张")) {
			if(null == length) {
				return Result.error("请输入长度。");
			}
			if(null == width) {
				return Result.error("请输入宽度。");
			}
			BigDecimal decimal100 = new BigDecimal("100");
			BigDecimal square = length.divide(decimal100, 4, BigDecimal.ROUND_DOWN)
					.multiply(width.divide(decimal100, 4, BigDecimal.ROUND_DOWN))
					.multiply(numberDecimal).setScale(2, BigDecimal.ROUND_DOWN);
			pageNum = numberDecimal;
			numberDecimal = square;
			//修改单位为平方
			LambdaQueryWrapper<BasMeasureUnit> query = new LambdaQueryWrapper<>();
			query.eq(BasMeasureUnit::getName, "平方");
			BasMeasureUnit newUnit = this.unitService.getOne(query);
			unit = newUnit;
		}

		BasMaterialCategory category = service.getById(categoryId);
		if(null == category) {
			return Result.error("未找到物料分类。");
		}
		String topCode = category.getCode();
		String userName = scanIo.getUserName();
		String model = scanIo.getModel();
		Date date = DateUtils.getDate();
		//备注信息
		String remark = scanIo.getRemark();
		List<BasMaterialTemp> addList = Lists.newArrayList();
		for (int i = 0; i < batchNum; i++) {
			String code = this.getCode(topCode);
			BasMaterialTemp material = new BasMaterialTemp();
			material.setCode(code);
			material.setCategoryId(categoryId);
			material.setName(category.getName());

			material.setUnitId(unit.getId());
			material.setSupplierId(category.getSupplierId());
			material.setAmount(numberDecimal);
			
			//获取物料相关宽度属性
			material.setModel(model);
			if(null == userName || userName.length() == 0) {
				LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				if(null != sysUser) {
					material.setCreateBy(sysUser.getUsername());
				}
			} else {
				material.setCreateBy(userName);
			}
			material.setCreateTime(date);
			material.setWidth(width);
			material.setLength(length);
			material.setRemark(remark);
			addList.add(material);
		}
		if(addList.size() > 0) {
			Result<Object> result = new Result<Object>();
			boolean isSuccess = this.tempService.saveBatch(addList);
			if(isSuccess) {
				List<Map<String, String>> resultList = Lists.newArrayList();
				Iterator<BasMaterialTemp> it = addList.iterator();
				String unitName = "";
//				BasMeasureUnit unit = this.unitService.getById(category.getUnitId());
				if(null != unit) {
					unitName = unit.getName();
				}
				String now = DateUtils.formatDate();
				while(it.hasNext()) {
					BasMaterialTemp material = it.next();
					String returnModel = material.getModel();
					Map<String, String> map = Maps.newHashMap();
					map.put("code", material.getCode());
					map.put("name", material.getName());
					map.put("model", returnModel);
					map.put("unit", unitName);
					if(null != pageNum) {
						map.put("pageNum", pageNum.toString());
					}
					BigDecimal amount = material.getAmount();
					if(null == number) {
						map.put("number", "");
					} else {
						map.put("number", amount.toString());
					}

					map.put("date", now);
					map.put("remark", remark == null ? StringUtils.EMPTY : remark);
					
					resultList.add(map);
				}
				result.setResult(resultList);
				return result.success("操作成功");
			}
		}
		return null;
	}

	@Override
	public String getOneMaterialIdByName(String materialName) {
		LambdaQueryWrapper<BasMaterial> query = new LambdaQueryWrapper<>();
		query.eq(BasMaterial::getName, materialName);
		List<BasMaterial> list = list(query);
		if(null != list && 0 != list.size()) {
			return list.get(0).getId();
		}
		return null;
	}

	@Override
	public List<BasMaterial> getByCategoryId(String categoryId) {
		LambdaQueryWrapper<BasMaterial> query = new LambdaQueryWrapper<>();
		query.eq(BasMaterial::getCategoryId, categoryId);
		return list(query);
	}

	@Override
	public Page<StkMaterielStorage> getMaterials(IPage<StkMaterielStorage> page,String warehouseId,
												 String parameter,String materialCode,
												 String width_begin,String width_end,String length_begin,String length_end,String order){
		List<String> basMaterialCategoryIdList = Lists.newArrayList();
		BasMaterialCategory basMaterialCategory = basMaterialCategoryMapper.selectById(parameter);
		if(basMaterialCategory != null){
			basMaterialCategoryIdList.add(basMaterialCategory.getId());
		}
		List<BasMaterialCategory> basMaterialCategories = basMaterialCategoryMapper.getAllChildCategoryHasChild(parameter);
		for(BasMaterialCategory bmc:basMaterialCategories){
			basMaterialCategoryIdList.add(bmc.getId());
		}
		Page<StkMaterielStorage> pageList = basMaterialMapper.getMaterials(page,warehouseId,basMaterialCategoryIdList,materialCode,width_begin,width_end,length_begin,length_end,order);
		if(pageList!=null && pageList.getSize()>0) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			for(StkMaterielStorage storage:pageList.getRecords()) {
				BasMaterialTemp temp = tempService.getByCode(storage.getMaterialCode());
				ZrkQzOrder qzOrder = orderService.getById(temp.getOrderId());
				if(qzOrder!=null) {
					if(StringUtils.equals("1300701144731623426", qzOrder.getProcessId()) 
							|| StringUtils.equals("1300701196116041729", qzOrder.getProcessId())) {
						storage.setQzProductDate(format.format(temp.getCreateTime()));
						String parentId = storage.getPid();
						while(StringUtils.isNotBlank(parentId)) {
							String[] pid = StringUtils.split(parentId, ",");
							BasMaterial basMaterial = this.getById(pid[0]);
							if(basMaterial==null) {
								break;
							}
							BasMaterialTemp materialTemp = tempService.getByCode(basMaterial.getCode());
							if(materialTemp!=null) {
								ZrkQzOrder zrkQzOrder = orderService.getById(materialTemp.getOrderId());
								if(zrkQzOrder!=null) {
									if(StringUtils.equals("1300701063685087234", zrkQzOrder.getProcessId())) {
										storage.setFqProductDate(format.format(materialTemp.getCreateTime()));
									}
									if(StringUtils.equals("1303963060735762433", zrkQzOrder.getProcessId())) {
										storage.setFhProductDate(format.format(materialTemp.getCreateTime()));
									}
									if(StringUtils.isNotBlank(materialTemp.getPid())) {
										String[] p = StringUtils.split(materialTemp.getPid(), ",");
										parentId = p[0];
									}else {
										break;
									}
								}else {
									break;
								}
							}else {
								break;
							}
						}
					}else if(StringUtils.equals("1300701063685087234", qzOrder.getProcessId())) {
						storage.setFqProductDate(format.format(temp.getCreateTime()));
						if(StringUtils.isNotBlank(storage.getPid())) {
							String parentId = storage.getPid();
							while(StringUtils.isNotBlank(parentId)) {
								String[] pid = StringUtils.split(parentId, ",");
								BasMaterial basMaterial = this.getById(pid[0]);
								if(basMaterial==null) {
									break;
								}
								BasMaterialTemp materialTemp = tempService.getByCode(basMaterial.getCode());
								if(materialTemp!=null) {
									ZrkQzOrder zrkQzOrder = orderService.getById(materialTemp.getOrderId());
									if(zrkQzOrder!=null) {
										if(StringUtils.equals("1300701063685087234", zrkQzOrder.getProcessId())) {
											storage.setFqProductDate(format.format(materialTemp.getCreateTime()));
										}
										if(StringUtils.equals("1303963060735762433", zrkQzOrder.getProcessId())) {
											storage.setFhProductDate(format.format(materialTemp.getCreateTime()));
										}
										if(StringUtils.isNotBlank(materialTemp.getPid())) {
											String[] p = StringUtils.split(materialTemp.getPid(), ",");
											parentId = p[0];
										}else {
											break;
										}
									}else {
										break;
									}
								}else {
									break;
								}
							}
						}
					}else if(StringUtils.equals("1303963060735762433", qzOrder.getProcessId())) {
						storage.setFhProductDate(format.format(temp.getCreateTime()));
					}
				}
				
			}
		}
		return pageList;
	}
	
	@Override
	public List<StkMaterielStorage> getMaterialsCount(String warehouseId,
												 String parameter,String materialCode,
												 String width_begin,String width_end,String length_begin,String length_end,String order){

		return basMaterialMapper.getMaterialsCount(warehouseId,parameter,materialCode,width_begin,width_end,length_begin,length_end,order);
	}

	@Override
	public Result<?> setMaterialFomula(String materialId, String fomulaId) {
		// TODO Auto-generated method stub
		if(StrUtil.isBlank(materialId) || StrUtil.isBlank(fomulaId)) {
			return Result.error("未选中物料或未分配配方");
		}
		String[] strings = StrUtil.split(materialId, ",");
		List<String> materialIdList = CollUtil.newArrayList(strings);
		materialIdList.add(UUID.randomUUID().toString());
		LambdaQueryWrapper<BasMaterial> query = new LambdaQueryWrapper<>();
		query.in(BasMaterial::getId, materialIdList);


		return Result.ok();
	}


	@Override
	public Page<StkMaterielStorage> countMateriels(Page<StkMaterielStorage> page, StkMaterielStorage storage){
		List<StkMaterielStorage> list = basMaterialMapper.sumQty(storage);
		if(StringUtils.equals(storage.getColumn(), "qty")) {
			if(StringUtils.equals(storage.getOrder(), "asc")) {
				list.sort(Comparator.comparing(StkMaterielStorage::getQty));
			}else if(StringUtils.equals(storage.getOrder(), "desc")) {
				list.sort(Comparator.comparing(StkMaterielStorage::getQty).reversed());
			}
		}
		if(StringUtils.equals(storage.getColumn(), "unitId_dictText")) {
			if(StringUtils.equals(storage.getOrder(), "asc")) {
				list.sort(Comparator.comparing(StkMaterielStorage::getUnitId));
			}else if(StringUtils.equals(storage.getOrder(), "desc")) {
				list.sort(Comparator.comparing(StkMaterielStorage::getUnitId).reversed());
			}
		}
		//截取集合
		if(null == list) {
			list = Lists.newArrayList();
		}
		long current = page.getCurrent();
		long size = page.getSize();
		long begin = (current-1) * size;
		long end = begin + size;
		int listSize = list.size();
		page.setTotal(listSize);
		List<StkMaterielStorage> records = Lists.newArrayList();
		if(listSize >= end) {
			for(int i = (int)begin; i < end; i++) {
				try {
					records.add(list.get(i));
				} catch (Exception e) {
					
				}
			}
		} else {
			for(int i = (int)begin; i < listSize; i++) {
				try {
					records.add(list.get(i));
				} catch (Exception e) {
					
				}
			}
		}
		return page.setRecords(records);
	}

	@Override
	public IPage<StkInventory> getSumQtyDetail(Page<StkInventory> page, StkMaterielStorage storage) {
		// TODO Auto-generated method stub
		return this.baseMapper.getSumQtyDetail(page, storage);
	}

	@Override
	public List<SumQtyVo> countMaterielsXls(String materialId, String pid,String materialName){

		return basMaterialMapper.sumQtyXls(materialId,pid,materialName);
	}

	@Override
	public List<SumQtyVo2> countMaterielsXls2(String materialId, String pid, String materialName){
		return basMaterialMapper.sumQtyXls2(materialId,pid,materialName);
	}

	@Override
	public List<String> getInvenMaterialIdsByCateId(String categoryId) {
		// TODO Auto-generated method stub
		return basMaterialMapper.getInvenMaterialIdsByCateId(categoryId);
	}

	@Override
	public BasMaterial getPurchaseMaterial(String materialId) {
		// TODO Auto-generated method stub
		return basMaterialMapper.getPurchaseMaterial(materialId);
	}

}
